package reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class test10 {
    //不使用反射创建对象测试执行时间
    public static void test1(){
        user user = new user();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("不使用反射创建对象测试执行时间"+(endTime-startTime)+"ms");
    }
    //使用反射创建对象,但不禁用安全检查测试执行时间
    public static void test2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> c = Class.forName("reflection.user");
        user user = (user)c.newInstance();
        Method method = c.getDeclaredMethod("getName",null);

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            method.invoke(user,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("使用反射创建对象,但不禁用安全检查测试执行时间"+(endTime-startTime)+"ms");
    }

    //使用反射创建对象,且禁用安全检查测试执行时间
    public static void test3() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> c = Class.forName("reflection.user");
        user user = (user)c.newInstance();
        Method method = c.getDeclaredMethod("getName",null);
        method.setAccessible(true);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000000; i++) {
            method.invoke(user,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("使用反射创建对象，且禁用安全检查测试执行时间"+(endTime-startTime)+"ms");
    }

    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        test1();
        test2();
        test3();
    }
}
